package com.eascs.admin.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * 操作Excel表格的功能类
 */
@SuppressWarnings("deprecation")
public class ExcelReader {
    private POIFSFileSystem fs;
    private InputStream is; 
    private HSSFWorkbook book;
    private HSSFSheet sheet;
    private HSSFRow row;
    
    public ExcelReader(File file) {
        try {
        	is = new FileInputStream(file);
        	fs = new POIFSFileSystem(is);
			book = new HSSFWorkbook(fs);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    public void close() {
    	if (is != null) {
    		try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
    	}
    }

    /**
     * 读取Excel表格表头的内容
     * @param InputStream
     * @return String 表头内容的数组
     */
    public String[] readTitle() {
    	return readCell(0);
    }
    
    public String[] readCell(int number) {
        sheet = book.getSheetAt(0);
        row = sheet.getRow(number);
        int cells = row.getPhysicalNumberOfCells(); // 标题总列数
        String[] objs = new String[cells];
        for (short i = 0; i < cells; i++) {
        	objs[i] = getStringCellValue(row.getCell(i));
        }
        return objs;
    }
    
    public List<String[]> readMatrix() {
    	sheet = book.getSheetAt(0);
        int rows = sheet.getLastRowNum(); 
        List<String[]> objs = new ArrayList<>();
        for (int i=0; i <= rows; i++) {
        	String[] cell = readCell(i);
        	objs.add(cell);
        }
        return objs;
    }

    /**
     * 获取单元格数据内容为字符串类型的数据
     * 
     * @param cell Excel单元格
     * @return String 单元格数据内容
     */
	
	private String getStringCellValue(HSSFCell cell) {
		if (cell == null) {
			return "";
		} else {
			switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			case HSSFCell.CELL_TYPE_NUMERIC:
				return String.valueOf(cell.getNumericCellValue());
			case HSSFCell.CELL_TYPE_BOOLEAN:
				return String.valueOf(cell.getBooleanCellValue());
			case HSSFCell.CELL_TYPE_BLANK:
				return "";
			default:
				return "";
			}
		}
	}

    public static void main(String[] args) {
		// 对读取Excel表格标题测试
	    File file = new File("d:\\营运中心各指标预算导入模板.xls");
		ExcelReader excel = new ExcelReader(file);
		List<String[]> readMatrix = excel.readMatrix();
		
		for (String[] strings : readMatrix) {
			System.out.println(strings.length);
			for (String string : strings) {
				System.out.print(string);
			}
			System.out.println();
		}
    }
}